package request;

import Constans.Constants;
import com.alibaba.fastjson.JSONObject;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:zhengyilong
 * @email:1797344574@qq.com
 * @phone:13479394730
 * @desc:该类用于实现rpc请求公共的代码部分
 * @DateTime:2021/12/15 11:27
 **/
public class RpcReq {

    public static String rpcReq(int id,String methed,Object... params){
        //准备rpc请求的用户身份信息，及对应的base64格式
        String author = Constants.BITCOIN_RPC_USER+":"+ Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();
        String authorBase64 = encoder.encodeToString(author.getBytes());

        //请求头的属性设置
        Map<String,String> header = new HashMap<>();
        header.put("ContentType","application/json");
        header.put("Authorization","Basic "+authorBase64);

        //准备rpc请求的数据
        Map<String,Object> body = new HashMap<>();
        body.put("id",id);
        body.put("method",methed);
        body.put("params",params);
        body.put("json_rpc","2.0");
        byte[] bodyBytes = JSONObject.toJSONBytes(body);

        //{"id":1001,"result":"xxx","error":null}
        String result = HttpUtil.post(Constants.BITCOIN_RPC_URL,header,bodyBytes);
        //将响应回来的数据返回
        return result;
    }

}

